package com.tinywind.boot.common.config.security;

import cn.dev33.satoken.exception.*;
import com.tinywind.boot.common.base.BaseResult;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @author liuxingyu01
 * @date 2022-03-24 8:43
 * @description 全局异常处理（sa-token抛的异常）
 **/
@RestControllerAdvice
public class SaTokenExceptionHandler {


    @ExceptionHandler(NotLoginException.class)
    public BaseResult handlerNotLoginException(NotLoginException nle) {
        // 不同异常返回不同状态码
        String message = "";
        if (nle.getType().equals(NotLoginException.NOT_TOKEN)) {
            message = "请提供Authorization";
        } else if (nle.getType().equals(NotLoginException.INVALID_TOKEN)) {
            message = "无效的Authorization";
        } else if (nle.getType().equals(NotLoginException.TOKEN_TIMEOUT)) {
            message = "会话已过期，请重新登录";
        } else if (nle.getType().equals(NotLoginException.BE_REPLACED)) {
            message = "您的账户已在另一台设备上登录，如非本人操作，请立即修改密码";
        } else if (nle.getType().equals(NotLoginException.KICK_OUT)) {
            message = "已被系统强制下线";
        } else {
            message = "当前会话未登录";
        }
        // 返回给前端
        return BaseResult.failure(BaseResult.CODE_NO_AUTHS, message);
    }

    @ExceptionHandler
    public BaseResult handlerNotRoleException(NotRoleException e) {
        return BaseResult.failure(BaseResult.CODE_NO_PERMISSION, "无权限访问：" + e.getRole());
    }

    @ExceptionHandler
    public BaseResult handlerNotPermissionException(NotPermissionException e) {
        return BaseResult.failure(BaseResult.CODE_NO_PERMISSION, "无权限访问：" + e.getCode());
    }

    @ExceptionHandler
    public BaseResult handlerDisableLoginException(DisableLoginException e) {
        return BaseResult.failure(BaseResult.CODE_NO_AUTHS, "账户被封禁：" + e.getDisableTime() + "秒后解封");
    }

    @ExceptionHandler
    public BaseResult handlerNotSafeException(NotSafeException e) {
        return BaseResult.failure(BaseResult.CODE_NO_AUTHS, "二级认证异常：" + e.getMessage());
    }
}
